#include <stdio.h>
#include <errno.h>
#include "i3.h"
#include "i3_client_api.h"
#include "utils.h"

int main(int argc, char **argv)
{ 
    int fd, rc, recv_seq;
    int seq = 0, to_send = 1;
    struct sockaddr_in local_addr;
    struct timeval select_time;
    fd_set rset;
    uint64_t rtt;
    uint32_t i3_addr, recv_i3_addr;
    uint16_t i3_port, recv_i3_port;

    /* addr and port as args */
    if (argc < 3) {
	printf("Usage: ping_test <i3_srv_addr> <i3_srv_port>\n");
	abort();
    }
    i3_addr = ntohl(inet_addr(argv[1]));
    i3_port = atoi(argv[2]);
    
    /* create socket */
    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	perror("socket");
	exit(-1);
    }
    
    memset((void *)&local_addr, 0, sizeof(struct sockaddr_in));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    local_addr.sin_port = htons(0);
    
    if (bind(fd, (struct sockaddr *) &local_addr, sizeof(struct sockaddr_in)) < 0) {
	perror("bind");
	exit(-1);
    }

    /* ping every second unto eternity */
    while (1) {
	if (to_send) 
	    i3_echo_request(fd, i3_addr, i3_port, seq++);
	
	FD_ZERO(&rset);
	FD_SET(fd, &rset);
	select_time.tv_sec = 0;
	select_time.tv_usec = 500000;
	if ((rc = select(fd+1, &rset, NULL, NULL, &select_time)) < 0) {
	    if (errno == EINTR) {
		to_send = 0;
		continue;
	    }
	    else {
		perror("select_error");
		exit(-1);
	    }
	}
	to_send = 1;
	if (rc > 0) {
	    struct in_addr ia;
	    recv_i3_echo_reply(fd, &recv_i3_addr, &recv_i3_port, &recv_seq, &rtt);
	    ia.s_addr = htonl(recv_i3_addr);
	    printf("Received echo reply from %s:%d - RTT of %Ld us\n",
		    inet_ntoa(ia), recv_i3_port, rtt);
	}
	
	sleep(1);
    }
    
    return -1;
}
